﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml.Serialization;
using flightquiz.Common;

namespace flightquiz.Data
{
    [Serializable]
    public class Excercise : IRender
    {
        public string Name { get; set; }

        public List<Question> Questions { get; set; }
        public List<Excercise> Papers { get; set; }

        public Excercise() 
            :this(string.Empty)
        { }
        public Excercise(string name) 
        { 
            this.Name = name;
            this.Questions = new List<Question>();
            this.Papers = new List<Excercise>();
        }

        public Excercise FindPaper(string name) 
        {
            foreach (var paper in Papers)
            {
                if (paper.Name == name)
                    return paper;
            }

            return null;
        }
        public void Load()
        {
            LoadTiku();
            LoadPapers();
        }
        public Excercise BuildPaper(string name, int count)
        {
            if (string.IsNullOrEmpty(name) || count <= 0)
                throw new Exception("Arguments invalid");

            Excercise paper = new Excercise(name);

            FillPaper(paper, count);
            SavePaper(paper);

            Papers.Add(paper);

            return paper;
        }

        private void LoadTiku()
        {
            string file = "题库.xls";

            DataSet dataset = new DataSet();

            string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + file + ";" + "Extended Properties=Excel 8.0;";
            using (OleDbConnection conn = new OleDbConnection(connectionString))
            {
                conn.Open();

                OleDbDataAdapter adapter = new OleDbDataAdapter("select * from [执照考试题库$]", conn);
                adapter.Fill(dataset, "table1");
            }

           //A.前15%，后38%  B.前18%，后36%  C.前24%，后34%
            Regex reg = new Regex(@"A\.(?<A>.*?)B\.(?<B>.*?)C\.(?<C>.*?)(D\.(?<D>.*))?", RegexOptions.IgnoreCase);

            foreach (DataRow row in dataset.Tables[0].Rows)
            {
                Match match = reg.Match(row[4].ToString());
                string correct = row[3].ToString().Trim('.', ' ').Trim().ToUpper();

                Answers answers = new Answers();
                answers.Add("A", match.Groups["A"].Value, correct);
                answers.Add("B", match.Groups["B"].Value, correct);
                answers.Add("C", match.Groups["C"].Value, correct);
                answers.Add("D", match.Groups["D"].Value, correct);

                Question question = new Question()
                {
                    ID = int.Parse(row[0].ToString()),
                    Title = row[2].ToString(),
                    Answers = answers
                };

                Questions.Add(question);
            };
        }
        private void LoadPapers()
        {
            if (!Directory.Exists("试卷"))
                Directory.CreateDirectory("试卷");

            foreach (var path in Directory.GetFiles("试卷", "*.xml"))
            {
                using (FileStream stream = new FileStream(path, FileMode.Open, FileAccess.Read))
                {
                    XmlSerializer ser = new XmlSerializer(typeof(Excercise));
                    var paper = ser.Deserialize(stream) as Excercise;

                    Papers.Add(paper);
                }
            }
        }
        private void SavePaper(Excercise paper)
        {
            if (paper != null)
            {
                if (!Directory.Exists("试卷"))
                    Directory.CreateDirectory("试卷");

                string fileTitle = paper.Name;
                foreach(var ch in Path.GetInvalidFileNameChars())
                {
                    fileTitle = fileTitle.Replace(ch+"","");
                }

                string path = Path.Combine("试卷",fileTitle+".xml");

                using (FileStream stream = new FileStream(path, FileMode.Create, FileAccess.Write))
                {
                    XmlSerializer ser = new XmlSerializer(typeof(Excercise));
                    ser.Serialize(stream, paper);
                }
            }
        }
        private void FillPaper(Excercise paper, int count)
        {
            for (int i = 0; i < count && i < Questions.Count; ++i)
            {
                paper.Questions.Add(Questions[i]);
            }
        }

        public string ToHTML()
        {
            StringBuilder sb = new StringBuilder();

            sb.Append("<h1>" + Name + "</h1>");
            foreach (var question in Questions)
            {
                sb.Append(question.ToHTML());
            }

            return sb.ToString();
        }
        public override string ToString()
        {
            return Name;
        }
    }
}
